package com.huasan.www.demon.rest.util;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Provider
public class RestRequestFilter implements ContainerRequestFilter{

	private static final Logger logger = LoggerFactory.getLogger(RestRequestFilter.class);
	
	public static final String JSON_TEMPLATE = "{\"status\":\"err\",\"data\":\"\", \"msg\":\"{0}\"}";
	
	@SuppressWarnings("restriction")
	private static final sun.misc.BASE64Decoder decode64 = new sun.misc.BASE64Decoder();
	
	@Override
	public void filter(ContainerRequestContext res) throws IOException {
		String path = res.getUriInfo().getRequestUri().getPath();
		String reqType = res.getHeaderString("Accept");
		
		if (reqType!=null && reqType.indexOf("javascript")!=-1){
			String userAgent = res.getHeaderString("User-Agent");
			for (int i=0; i<Constants.AGENTS.length; i++){
				if (userAgent!=null && userAgent.toLowerCase().indexOf(Constants.AGENTS[i])!=-1){
					String datatype = res.getHeaderString("datatype");
					if (!Constants.DATA_TYPE.equals(datatype)){
						res.abortWith(getErrRes("数据类型错误"));
					}else{
						if (path.indexOf("/login")==-1){
							String userid = res.getHeaderString("userid");
							if (userid==null || "".equals(userid)){
								res.abortWith(getErrRes("用户认证失败"));
							} 
						}else if (path.indexOf("/register")!=-1){
							String register = res.getHeaderString("regtype");
							if (!Constants.DATA_REGISTER.equals(register)){
								res.abortWith(getErrRes("注册认证失败"));
							}
						}
					}
				}
			}
		}
		
//		String auth = res.getHeaderString("Authorization");
//		logger.debug(auth);
//		logger.error(auth);
//		logger.debug("validate user:" + auth(auth));
	}

	private boolean auth(String auth){
		if (auth==null){
			return false;
		}
		if (!auth.toUpperCase().startsWith("BASIC ")){
			return false;
		}
		String credentialsEncode = auth.substring(6);
		try {
			String[] credentials = new String(decode64.decodeBuffer(credentialsEncode))
														.split(":");
			logger.debug("User:" + credentials[0]);
			logger.debug("Pass:" + credentials[1]);
			return true;
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return false;
		}
	}
	
	private Response getErrRes(String msg){
		return Response.status(500).entity(JSON_TEMPLATE.replace("{0}", msg)).build();
	}
	
}
